package com.unionfetch.content_home.ui.step

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.alibaba.android.arouter.launcher.ARouter
import com.sumsub.sns.internal.features.data.model.esign.e
import com.unionfetch.content_home.R
import com.unionfetch.content_home.bean.Gender
import com.unionfetch.content_home.bean.RightWrongInfo
import com.unionfetch.content_home.bean.request.FirstStepRequest
import com.unionfetch.content_home.contract.OpenAccountContract
import com.unionfetch.content_home.presenter.OpenAccountPresenter
import com.unionfetch.content_home.ui.dialog.CustomSelectDialog
import com.unionfetch.content_home.ui.dialog.CustomTipDialog
import com.unionfetch.content_home.ui.fragment.HomeFragment
import com.unionftech.common.CommonConstants
import com.unionftech.common.R.dimen
import com.unionftech.common.R.string
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.base.mvp.impl.IBaseCallBack
import com.unionftech.common.bean.ApiException
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.bean.toastTimeout
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.bean.CountryInfo
import com.unionftech.common.common.bean.PhoneRegexInfo
import com.unionftech.common.common.bean.SystemUserInfo
import com.unionftech.common.common.bean.request.SendCodeRequest
import com.unionftech.common.common.contract.CommonContract
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.common.model.CommonModel
import com.unionftech.common.common.presenter.CommonPresenter
import com.unionftech.common.common.ui.UFCountryCodeSelectDialogFragment
import com.unionftech.common.router.RouterPath
import com.unionftech.common.utils.CheckInputUtil
import com.unionftech.common.utils.ExtentUtil
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.RegexUtils
import com.unionftech.common.utils.SignUtils
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.Utils
import com.unionftech.common.utils.countDown
import com.unionftech.common.utils.formatToDateString
import kotlinx.coroutines.CoroutineScope
import java.util.Calendar

class FirstStepOpenAccountActivity : BaseMvpActivity(), IUpdate, CommonContract.ISendCodeView,
    OpenAccountContract.IFirstStepView {

    private val mBtnNext by lazy { findViewById<Button>(R.id.btn_next) }
    private val mTvInvitationCodeError by lazy { findViewById<TextView>(R.id.tv_invitation_code_error) }
    private val mIvClearInvitationCode by lazy { findViewById<ImageView>(R.id.iv_clear_invitation_code) }
    private val mEtInvitationCode by lazy { findViewById<EditText>(R.id.et_invitation_code) }
    private val mTvInvitationCodeTitle by lazy { findViewById<TextView>(R.id.tv_invitation_code_title) }
    private val mLlInvitationCodeContainer by lazy { findViewById<LinearLayout>(R.id.ll_invitation_code_container) }
    private val mTvIdCardError by lazy { findViewById<TextView>(R.id.tv_id_card_error) }
    private val mIvClearIdCard by lazy { findViewById<ImageView>(R.id.iv_clear_id_card) }
    private val mEtIdCard by lazy { findViewById<EditText>(R.id.et_id_card) }
    private val mTvIdCardTitle by lazy { findViewById<TextView>(R.id.tv_id_card_title) }
    private val mLlIdCardContainer by lazy { findViewById<LinearLayout>(R.id.ll_id_card_container) }
    private val mTvGenderError by lazy { findViewById<TextView>(R.id.tv_gender_error) }
    private val mEtGender by lazy { findViewById<TextView>(R.id.et_gender) }
    private val mRlGenderInputContainer by lazy { findViewById<RelativeLayout>(R.id.rl_gender_input_container) }
    private val mTvGenderTitle by lazy { findViewById<TextView>(R.id.tv_gender_title) }
    private val mLlGenderContainer by lazy { findViewById<LinearLayout>(R.id.ll_gender_container) }
    private val mTvBirthdayError by lazy { findViewById<TextView>(R.id.tv_birthday_error) }
    private val mEtBirthday by lazy { findViewById<TextView>(R.id.et_birthday) }
    private val mRlBirthdayInputContainer by lazy { findViewById<RelativeLayout>(R.id.rl_birthday_input_container) }
    private val mTvBirthdayTitle by lazy { findViewById<TextView>(R.id.tv_birthday_title) }
    private val mLlBirthdayContainer by lazy { findViewById<LinearLayout>(R.id.ll_birthday_container) }
    private val mTvOtherSecondNameError by lazy { findViewById<TextView>(R.id.tv_other_second_name_error) }
    private val mIvOtherClearSecondName by lazy { findViewById<ImageView>(R.id.iv_other_clear_second_name) }
    private val mEtOtherSecondName by lazy { findViewById<EditText>(R.id.et_other_second_name) }
    private val mTvOtherSecondNameTitle by lazy { findViewById<TextView>(R.id.tv_other_second_name_title) }
    private val mLlOtherSecondNameContainer by lazy { findViewById<LinearLayout>(R.id.ll_other_second_name_container) }
    private val mTvOtherFirstNameError by lazy { findViewById<TextView>(R.id.tv_other_first_name_error) }
    private val mIvOtherClearFirstName by lazy { findViewById<ImageView>(R.id.iv_other_clear_first_name) }
    private val mEtOtherFirstName by lazy { findViewById<EditText>(R.id.et_other_first_name) }
    private val mTvOtherFirstNameTitle by lazy { findViewById<TextView>(R.id.tv_other_first_name_title) }
    private val mLlOtherFirstNameContainer by lazy { findViewById<LinearLayout>(R.id.ll_other_first_name_container) }
    private val mTvSecondNameError by lazy { findViewById<TextView>(R.id.tv_second_name_error) }
    private val mIvClearSecondName by lazy { findViewById<ImageView>(R.id.iv_clear_second_name) }
    private val mEtSecondName by lazy { findViewById<EditText>(R.id.et_second_name) }
    private val mTvSecondNameTitle by lazy { findViewById<TextView>(R.id.tv_second_name_title) }
    private val mLlSecondNameContainer by lazy { findViewById<LinearLayout>(R.id.ll_second_name_container) }
    private val mTvFirstNameError by lazy { findViewById<TextView>(R.id.tv_first_name_error) }
    private val mIvClearFirstName by lazy { findViewById<ImageView>(R.id.iv_clear_first_name) }
    private val mEtFirstName by lazy { findViewById<EditText>(R.id.et_first_name) }
    private val mTvFirstNameTitle by lazy { findViewById<TextView>(R.id.tv_first_name_title) }
    private val mLlFirstNameContainer by lazy { findViewById<LinearLayout>(R.id.ll_first_name_container) }
    private val mTvCodeError by lazy { findViewById<TextView>(R.id.tv_code_error) }
    private val mIvClearVerifyCode by lazy { findViewById<ImageView>(R.id.iv_clear_verify_code) }
    private val mTvSendCode by lazy { findViewById<TextView>(R.id.tv_send_code) }
    private val mEtVerificationCode by lazy { findViewById<EditText>(R.id.et_verification_code) }
    private val mTvVerifyCodeTitle by lazy { findViewById<TextView>(R.id.tv_verify_code_title) }
    private val mTvEmailError by lazy { findViewById<TextView>(R.id.tv_email_error) }
    private val mIvClearEmail by lazy { findViewById<ImageView>(R.id.iv_clear_email) }
    private val mEtEmail by lazy { findViewById<EditText>(R.id.et_email) }
    private val mTvEmailTitle by lazy { findViewById<TextView>(R.id.tv_email_title) }
    private val mLlEmailContainer by lazy { findViewById<LinearLayout>(R.id.ll_email_container) }
    private val mTvPhoneError by lazy { findViewById<TextView>(R.id.tv_phone_error) }
    private val mIvClearPhone by lazy { findViewById<ImageView>(R.id.iv_clear_phone) }
    private val mTvCountryCode by lazy { findViewById<TextView>(R.id.tv_country_code) }
    private val mLlCountryCode by lazy { findViewById<LinearLayout>(R.id.ll_country_code) }
    private val mEtPhone by lazy { findViewById<EditText>(R.id.et_phone) }
    private val mTvContactPhoneTitle by lazy { findViewById<TextView>(R.id.tv_contact_phone_title) }
    private val mLlContactPhoneContainer by lazy { findViewById<LinearLayout>(R.id.ll_contact_phone_container) }
    private val mTvIsslamicAccountError by lazy { findViewById<TextView>(R.id.tv_isslamic_account_error) }
    private val mEtIsslamicAccount by lazy { findViewById<TextView>(R.id.et_isslamic_account) }
    private val mRlIsslamicAccountInputContainer by lazy { findViewById<RelativeLayout>(R.id.rl_isslamic_account_input_container) }
    private val mTvIsslamicAccountTitle by lazy { findViewById<TextView>(R.id.tv_isslamic_account_title) }
    private val mLlIsslamicAccountContainer by lazy { findViewById<LinearLayout>(R.id.ll_isslamic_account_container) }
    private val mTvCountryError by lazy { findViewById<TextView>(R.id.tv_country_error) }
    private val mEtCountry by lazy { findViewById<TextView>(R.id.et_country) }
    private val mRlCountryInputContainer by lazy { findViewById<RelativeLayout>(R.id.rl_country_input_container) }
    private val mTvCountryTitle by lazy { findViewById<TextView>(R.id.tv_country_title) }
    private val mLlCountryContainer by lazy { findViewById<LinearLayout>(R.id.ll_country_container) }
    private val mTvBaseInfoTitle by lazy { findViewById<TextView>(R.id.tv_base_info_title) }

    private val mIvBack by lazy { findViewById<ImageView>(R.id.iv_step_back) }
    private val mIvCustomer by lazy { findViewById<ImageView>(R.id.iv_customer) }

    private var mCountryCodeDialog: UFCountryCodeSelectDialogFragment? = null
    private var mCurrentCountryId: Int = -1
    private var mCountryInfo: CountryInfo? = null
    private var mPhoneCountryInfo: CountryInfo? = null
    private val mPhoneRegexMap = mutableMapOf<String, String>()
    private var mCountDown: CoroutineScope? = null
    private var mPublicKeyStr: String = ""
    private var mCustomSelectDialog: CustomSelectDialog? = null
    private var mIsShowLoading = false
    private val mCommonModel by lazy { CommonModel() }

    //伊斯兰账户选择
    private var mIsslamicSelectIndex = -1

    //性别选择
    private var mGenderSelectIndex = -1

    @InjectPresenter
    private lateinit var mOpenPresenter: OpenAccountPresenter

    @InjectPresenter
    private lateinit var mCommonPresenter: CommonPresenter


    companion object {
        /**
         * 展示伊斯兰账户选项的国家和地区（code）
         * Malaysia（马来西亚） 或 Indonesia（印度尼西亚）
         */
        private val SHOW_ISSLAMIC_ACCOUNT_LIST = listOf("MYS", "INA")

        /**
         * 展示 姓（中文）和 姓（拼音）的国家和地区(code)
         *
         * 中国大陆/香港
         */
        private val SHOW_PINYIN_LIST = listOf("CHN", "HKG")

        /**
         * 展示姓（韩文）的国家和地区(code)
         * 韩国
         */
        private val SHOW_KOREAN_LIST = listOf("KOR")

        @JvmStatic
        fun startThis(context: Context) {
            Intent(context, FirstStepOpenAccountActivity::class.java).apply {
                if (context !is Activity) {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                context.startActivity(this)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun initLayout() = R.layout.activity_first_step_open_account

    override fun initLanguageText() {
        super.initLanguageText()
        mTvBaseInfoTitle.text = DynamicResourceManager.getString(mContext, string.base_info)
        mTvCountryTitle.text =
            DynamicResourceManager.getString(mContext, string.country_of_residence)
        mEtCountry.hint = DynamicResourceManager.getString(string.please_select)
        mTvIsslamicAccountTitle.text =
            DynamicResourceManager.getString(mContext, string.isslamic_account)
        mEtIsslamicAccount.hint = DynamicResourceManager.getString(string.please_select)
        mTvContactPhoneTitle.text =
            DynamicResourceManager.getString(mContext, string.contact_phone)
        mTvEmailTitle.text = DynamicResourceManager.getString(mContext, string.email)
        mEtEmail.hint = DynamicResourceManager.getString(string.please_input)
        mTvVerifyCodeTitle.text = DynamicResourceManager.getString(
            mContext, string.verification_code
        )
        mTvSendCode.text = DynamicResourceManager.getString(string.send_OTP)
        mEtVerificationCode.hint = DynamicResourceManager.getString(string.please_input)
        mTvFirstNameTitle.text = DynamicResourceManager.getString(mContext, string.first_name)
        mEtFirstName.hint = DynamicResourceManager.getString(string.please_input)
        mEtOtherFirstName.hint = DynamicResourceManager.getString(string.please_input)
        mTvSecondNameTitle.text = DynamicResourceManager.getString(mContext, string.second_name)
        mEtSecondName.hint = DynamicResourceManager.getString(string.please_input)
        mEtOtherSecondName.hint = DynamicResourceManager.getString(string.please_input)
        mTvBirthdayTitle.text = DynamicResourceManager.getString(mContext, string.birthday)
        mEtBirthday.hint = DynamicResourceManager.getString(string.please_select)
        mTvGenderTitle.text = DynamicResourceManager.getString(mContext, string.gender)
        mEtGender.hint = DynamicResourceManager.getString(string.please_select)
        mTvIdCardTitle.text = DynamicResourceManager.getString(mContext, string.id_card_no)
        mEtIdCard.hint = DynamicResourceManager.getString(string.please_input)
        mTvInvitationCodeTitle.text =
            DynamicResourceManager.getString(mContext, string.invitation_code)
        mEtInvitationCode.hint = DynamicResourceManager.getString(string.please_input)

    }

    override fun needShowLoading(): Boolean {
        return mIsShowLoading
    }

    override fun setListener() {
        super.setListener()
        mIvBack.setOnClickListener(this)
        mIvCustomer.setOnClickListener(this)
        mRlCountryInputContainer.setOnClickListener(this)
        mRlIsslamicAccountInputContainer.setOnClickListener(this)
        mTvSendCode.setOnClickListener(this)
        mLlCountryCode.setOnClickListener(this)
        mRlBirthdayInputContainer.setOnClickListener(this)
        mRlGenderInputContainer.setOnClickListener(this)
        mBtnNext.setOnClickListener(this)

        mIvClearPhone.setOnClickListener {
            mEtPhone.setText("")
        }
        addTextChangeListener(mEtPhone, mIvClearPhone)
        addFocusChangeListener(mEtPhone, mIvClearPhone)

        mIvClearEmail.setOnClickListener {
            mEtEmail.setText("")
        }
        addTextChangeListener(mEtEmail, mIvClearEmail)
        addFocusChangeListener(mEtEmail, mIvClearEmail)

        mIvClearVerifyCode.setOnClickListener {
            mEtVerificationCode.setText("")
        }
        addTextChangeListener(mEtVerificationCode, mIvClearVerifyCode)
        addFocusChangeListener(mEtVerificationCode, mIvClearVerifyCode)

        mIvClearFirstName.setOnClickListener {
            mEtFirstName.setText("")
        }
        addTextChangeListener(mEtFirstName, mIvClearFirstName)
        addFocusChangeListener(mEtFirstName, mIvClearFirstName)

        mIvClearSecondName.setOnClickListener {
            mEtSecondName.setText("")
        }
        addTextChangeListener(mEtSecondName, mIvClearSecondName)
        addFocusChangeListener(mEtSecondName, mIvClearSecondName)

        mIvOtherClearFirstName.setOnClickListener {
            mEtOtherFirstName.setText("")
        }
        addTextChangeListener(mEtOtherFirstName, mIvOtherClearFirstName)
        addFocusChangeListener(mEtOtherFirstName, mIvOtherClearFirstName)

        mIvOtherClearSecondName.setOnClickListener {
            mEtOtherSecondName.setText("")
        }
        addTextChangeListener(mEtOtherSecondName, mIvOtherClearSecondName)
        addFocusChangeListener(mEtOtherSecondName, mIvOtherClearSecondName)

        mIvClearIdCard.setOnClickListener {
            mEtIdCard.setText("")
        }
        addTextChangeListener(mEtIdCard, mIvClearIdCard)
        addFocusChangeListener(mEtIdCard, mIvClearIdCard)

        mIvClearInvitationCode.setOnClickListener {
            mEtInvitationCode.setText("")
        }
        addTextChangeListener(mEtInvitationCode, mIvClearInvitationCode)
        addFocusChangeListener(mEtInvitationCode, mIvClearInvitationCode)
        GlobalInfoManager.getInstance().addListener(this)
    }

    private fun addTextChangeListener(editText: EditText, clearView: ImageView? = null) {
        editText.addTextChangedListener { text ->
            if (text.toString().contains(" ")) {
                val str = text?.toString()?.split(" ")
                val sb = StringBuffer()
                for (i in 0 until str?.size!!) {
                    sb.append(str[i])
                }
                editText.setText(sb.toString())
                editText.setSelection(sb.toString().length)
            }
            setClearView(editText.text, clearView)
            checkButtonEnable()
        }
    }

    private fun checkButtonEnable() {
        val emailInputValue = if (mLlEmailContainer.isShown) {
            !TextUtils.isEmpty(mEtEmail.text) && !TextUtils.isEmpty(mEtVerificationCode.text)
        } else {
            true
        }
        val firstOtherInputValue = if (mLlOtherFirstNameContainer.isShown) {
            !TextUtils.isEmpty(mEtOtherFirstName.text)
        } else {
            true
        }
        val secondOtherInputValue = if (mLlOtherSecondNameContainer.isShown) {
            !TextUtils.isEmpty(mEtOtherSecondName.text)
        } else {
            true
        }
        val enable =
            !TextUtils.isEmpty(mEtCountry.text) && !TextUtils.isEmpty(mEtPhone.text) && emailInputValue && !TextUtils.isEmpty(
                mEtFirstName.text
            ) && !TextUtils.isEmpty(mEtSecondName.text) && firstOtherInputValue && secondOtherInputValue && !TextUtils.isEmpty(
                mEtBirthday.text
            ) && !TextUtils.isEmpty(mEtGender.text) && !TextUtils.isEmpty(mEtIdCard.text)
        mBtnNext.isEnabled = enable
    }

    private fun addFocusChangeListener(
        editText: EditText, clearView: ImageView? = null
    ) {
        editText.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                //去除错误边框展示
                editText.isSelected = false
                setClearView(editText.text, clearView)
                if (editText == mEtInvitationCode) {
                    mTvInvitationCodeError.visibility = View.INVISIBLE
                    mTvInvitationCodeError.text = ""
                }
            } else {
                clearView?.visibility = View.GONE
                checkInput(editText)
                if (editText == mEtInvitationCode) {
                    checkInvitationCode()
                }
                covertToPinyin(editText)
            }
        }
    }

    private fun covertToPinyin(editText: EditText) {
        if (editText == mEtOtherSecondName
            || editText == mEtOtherFirstName
        ) {
            val inputStr = editText.text.toString()
            if (Utils.isContainChinese(inputStr)
                && SHOW_PINYIN_LIST.contains(mCountryInfo?.code ?: "")
            ) {
                val convertToPinyin = Utils.convertToPinyin(inputStr)
                if (editText == mEtOtherSecondName) {
                    mEtSecondName.setText(convertToPinyin)
                } else {
                    mEtFirstName.setText(convertToPinyin)
                }
            }
        }
    }

    private fun setClearView(text: Editable?, clearView: ImageView?) {
        if (!TextUtils.isEmpty(text)) {
            clearView?.visibility = View.VISIBLE
        } else {
            clearView?.visibility = View.GONE
        }
    }


    private fun checkInput(editText: EditText): Boolean {
        when (editText) {
            mEtPhone -> {
                if (mPhoneCountryInfo == null) {
                    mEtPhone.isSelected = true
                    mTvPhoneError.visibility = View.VISIBLE
                    mTvPhoneError.text = DynamicResourceManager.getString(
                        mTvPhoneError.context, string.please_select
                    )
                    return false
                } else {
                    return CheckInputUtil.checkPhoneInput(
                        mEtPhone.text.toString(),
                        mPhoneCountryInfo!!.areaCode,
                        mPhoneRegexMap[mPhoneCountryInfo!!.areaCode] ?: "",
                        mEtPhone,
                        mTvPhoneError,
                        string.phone_empty,
                        string.phone_format_incorrect
                    )
                }
            }

            mEtEmail -> return CheckInputUtil.checkInput(
                mEtEmail.text.toString(),
                RegexUtils.EMAIL_REGEX,
                mEtEmail,
                mTvEmailError,
                string.email_empty,
                string.email_format_incorrect
            )

            mEtVerificationCode -> return CheckInputUtil.checkInput(
                mEtVerificationCode.text.toString(),
                RegexUtils.VERIFYCODE_REGEX,
                mEtVerificationCode,
                mTvCodeError,
                string.verification_code_empty,
                string.verification_code_incorrect
            )

            mEtFirstName -> return CheckInputUtil.checkPinYinInput(
                mEtFirstName.text.toString(),
                mCountryInfo?.code ?: "",
                mEtFirstName,
                mTvFirstNameError,
                string.item_cannot_empty,
                string.incorrect_format
            )

            mEtSecondName -> return CheckInputUtil.checkPinYinInput(
                mEtSecondName.text.toString(),
                mCountryInfo?.code ?: "",
                mEtSecondName,
                mTvSecondNameError,
                string.item_cannot_empty,
                string.incorrect_format
            )

            mEtOtherFirstName -> return CheckInputUtil.checkChineseInput(
                mCountryInfo?.code ?: "",
                mEtOtherFirstName.text.toString(),
                mEtOtherFirstName,
                mTvOtherFirstNameError,
                string.item_cannot_empty,
                string.incorrect_format
            )

            mEtOtherSecondName -> return CheckInputUtil.checkChineseInput(
                mCountryInfo?.code ?: "",
                mEtOtherSecondName.text.toString(),
                mEtOtherSecondName,
                mTvOtherSecondNameError,
                string.item_cannot_empty,
                string.incorrect_format
            )

            mEtIdCard -> return CheckInputUtil.checkIdCardInput(
                mEtIdCard.text.toString(),
                mCountryInfo?.code ?: "",
                mEtIdCard,
                mTvIdCardError,
                string.item_cannot_empty,
                string.id_no_incorrect
            )
        }
        return true
    }

    override fun setView() {
        super.setView()
        //editText的左右padding不一致，目前只能在代码中设置，在xml中设置不支持rtl
        val dp16 = mContext.resources.getDimension(dimen.dp_16).toInt()
        val dp48 = mContext.resources.getDimension(dimen.dp_48).toInt()
        mEtEmail.setPaddingRelative(dp16, 0, dp48, 0)
        hideTitleBar()
        loadData()
        updateInitView()
    }

    private fun updateInitView() {
        val systemUserInfo = GlobalInfoManager.getInstance().getSystemUserInfo()
        systemUserInfo?.also { info ->
            //当注册为邮箱时，不显示邮箱模块。
            if (!TextUtils.isEmpty(info.email)) {
                mLlEmailContainer.visibility = View.GONE
            } else {
                mLlEmailContainer.visibility = View.VISIBLE
            }
            //如果注册页面已填写有效的邀请码，不显示此模块；
            if (!TextUtils.isEmpty(info.invitationCode)) {
                mLlInvitationCodeContainer.visibility = View.GONE
            } else {
                mLlInvitationCodeContainer.visibility = View.VISIBLE
            }
        }
        mBtnNext.isEnabled = false
    }

    override fun loadData() {
        super.loadData()
        getPublicKey()
        getCountryInfoByIp()
        updateAllPhoneRegex()
    }

    private fun getPublicKey() {
        val publicKeyStr = GlobalInfoManager.getInstance().getPublicKeyStr()
        if (!TextUtils.isEmpty(publicKeyStr)) {
            mPublicKeyStr = publicKeyStr
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_PUBLIC_KEY)
        }
    }

    private fun getCountryInfoByIp() {
        val countryInfo = GlobalInfoManager.getInstance().getCountryInfo()
        if (countryInfo != null) {
            updateCountryInfoByIp(countryInfo)
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_COUNTRY_INFO)
        }
    }

    private fun updateAllPhoneRegex() {
        val list = GlobalInfoManager.getInstance().getAllPhoneRegex()
        if (list.isNotEmpty()) {
            mPhoneRegexMap.clear()
            for (info in list) {
                mPhoneRegexMap[info.areaCode] = info.regex
            }
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_ALL_PHONE_REGEX)
        }
    }


    override fun onUpdate(obj: Any?) {
        if (obj is List<*>) {
            updatePhoneRegex(obj)
        } else if (obj is CountryInfo) {
            updateCountryInfoByIp(obj)
        } else if (obj is String) {
            mPublicKeyStr = obj
        } else if (obj is SystemUserInfo) {
            SecondStepOpenAccountActivity.startThis(mContext)
            finish()
        }
    }

    private fun updatePhoneRegex(list: List<*>) {
        mPhoneRegexMap.clear()
        for (info in list) {
            if (info is PhoneRegexInfo) {
                mPhoneRegexMap[info.areaCode] = info.regex
            }
        }
    }

    private fun updateCountryInfoByIp(countryInfo: CountryInfo) {
        mPhoneCountryInfo = countryInfo
        mTvCountryCode.text = countryInfo.areaCode
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.iv_step_back -> {
                showLeaveDialog()
            }

            R.id.iv_customer -> {
                ToastUtils.longToast(
                    DynamicResourceManager.getString(
                        mContext, string.developing
                    )
                )
            }

            R.id.rl_country_input_container -> {
                //选择居住地区
                mCurrentCountryId = v.id
                showCountryCodeDialog()
            }

            R.id.rl_isslamic_account_input_container -> {
                //选择伊斯兰账户
                showIsslamicDilaog()
            }

            R.id.ll_country_code -> {
                //选择手机号地区
                mCurrentCountryId = v.id
                showCountryCodeDialog()
            }

            R.id.tv_send_code -> {
                //发送邮箱验证码
                sendCode()
            }

            R.id.rl_birthday_input_container -> {
                //选择生日
                showDatePickDlg()
            }

            R.id.rl_gender_input_container -> {
                //选择性别
                showGenderDialog()
            }

            R.id.btn_next -> {
                // 提交表单，进入下一步
                submit()
            }
        }
    }

    /**
     * 屏蔽物理返回键
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            showLeaveDialog()
            true
        } else super.onKeyDown(keyCode, event)
    }

    private fun submit() {
        getRequestBean()?.also { request ->
            mIsShowLoading = true
            showLoading()
            //校验邀请码
            checkInvitationCode { result ->
                if (result) {
                    requestSubmit(request)
                }
            }
        }
    }

    private fun checkInvitationCode(callback: ((Boolean) -> Unit)? = null) {
        if (TextUtils.isEmpty(mEtInvitationCode.text)) {
            callback?.invoke(true)
            return
        }
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mCommonModel.checkInvitationCode(userToken,
            mEtInvitationCode.text.toString(),
            object : IBaseCallBack<ResponseResult<Any?>> {
                override fun onResponse(response: ResponseResult<Any?>) {
                    callback?.invoke(response.code == ResponseResult.SUCCESS_CODE)
                    if (response.code == ResponseResult.SUCCESS_CODE) {
                        mEtInvitationCode.isSelected = false
                        mTvInvitationCodeError.visibility = View.INVISIBLE
                        mTvInvitationCodeError.text = ""
                    } else {
                        hideLoading()
                        mIsShowLoading = false
                        mEtInvitationCode.isSelected = true
                        mTvInvitationCodeError.visibility = View.VISIBLE
                        mTvInvitationCodeError.text =
                            DynamicResourceManager.getString(string.invitation_code_invalid)
                    }
                }
            })
    }

    private fun requestSubmit(request: FirstStepRequest) {
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mOpenPresenter.submitFirstStep(userToken, request)
    }

    private fun getRequestBean(): FirstStepRequest? {
        if (!checkSubmit()) {
            return null
        }
        return FirstStepRequest().apply {
            //居住区
            residence = mCountryInfo!!.code
            //伊斯兰账户
            if (mLlIsslamicAccountContainer.isShown) {
                RightWrongInfo.entries.getOrNull(mIsslamicSelectIndex)?.also {
                    typeIslam = it.value
                }
            }
            //联系人
            contactPhone = mEtPhone.text.toString()
            areaCode = mPhoneCountryInfo!!.areaCode
            //邮箱
            if (mLlEmailContainer.isShown) {
                loginEmail = mEtEmail.text.toString()
                verifyCode = mEtVerificationCode.text.toString()
            }
            //姓名
            firstNameEn = mEtSecondName.text.toString() //名
            lastNameEn = mEtFirstName.text.toString()//姓
            fullNameEn = "$firstNameEn $lastNameEn"
            fullNameLocal = "$firstNameEn $lastNameEn"
            //中文姓名、韩文姓名
            if (mLlOtherFirstNameContainer.isShown) {
                firstNameLocal = mEtOtherSecondName.text.toString() //名（中文）
                lastNameLocal = mEtOtherFirstName.text.toString()//姓（中文）
            }
            //完整的名字
            if (mLlOtherFirstNameContainer.isShown) {
                fullNameLocal = "$lastNameLocal$firstNameLocal" //姓+名
            }
            //生日
            birthday = mEtBirthday.text.toString()
            //性别
            Gender.entries.getOrNull(mGenderSelectIndex)?.also {
                userSex = it.type
            }
            //身份证号
            SignUtils.encrypt(
                SignUtils.loadPublicKeyByStr(mPublicKeyStr), mEtIdCard.text.toString().toByteArray()
            )?.also {
                identifyId = it
            }
            //邀请码
            invitationCode = mEtInvitationCode.text.toString()
        }
    }

    private fun checkSubmit(): Boolean {
        var result = true
        //居住地
        if (mCountryInfo == null || TextUtils.isEmpty(mEtCountry.text)) {
            result = false
        }
        //【伊斯兰账户】
        if (mLlIsslamicAccountContainer.isShown && TextUtils.isEmpty(mEtIsslamicAccount.text)) {
            result = false
        }
        //联系人手机号
        if (!checkInput(mEtPhone)) {
            result = false
        }
        //邮箱
        if (mLlEmailContainer.isShown) {
            if (!checkInput(mEtEmail)) {
                result = false
            }
            if (!checkInput(mEtVerificationCode)) {
                result = false
            }
        }
        if (mLlOtherSecondNameContainer.isShown) {
            if (!checkInput(mEtOtherSecondName)) {
                result = false
            }
        }
        if (mLlOtherFirstNameContainer.isShown) {
            if (!checkInput(mEtOtherFirstName)) {
                result = false
            }
        }
        //姓名
        if (!checkInput(mEtSecondName)) {
            result = false
        }
        if (!checkInput(mEtFirstName)) {
            result = false
        }
        //生日
        if (TextUtils.isEmpty(mEtBirthday.text)) {
            result = false
        }
        //身份证
        if (!checkInput(mEtIdCard)
            || TextUtils.isEmpty(mPublicKeyStr)
        ) {
            result = false
        }
        return result
    }

    private fun showLeaveDialog() {
        val dialog = CustomTipDialog(mContext)
        dialog.setTopRes(R.drawable.ic_circle_warning)
            .setTitle(DynamicResourceManager.getString(mContext, string.confirm_leave))
            .setCancelText(
                DynamicResourceManager.getString(
                    mContext, string.cancel
                )
            ).setConfirmText(
                DynamicResourceManager.getString(
                    mContext, string.confirm
                )
            ).setCallBack { confirm ->
                if (confirm) {
                    gotoMain()
                }
                dialog.dismiss()
            }.show()
    }

    private fun gotoMain() {
        ARouter.getInstance().build(RouterPath.UFUFMainStandardActivityInfo.PATH).navigation()
        finish()
    }


    /**
     * 展示伊斯兰账户选择
     */
    private fun showIsslamicDilaog() {
        if (mCustomSelectDialog == null) {
            mCustomSelectDialog = CustomSelectDialog(mContext)
        }
        val list = mutableListOf<String>()
        for (item in RightWrongInfo.entries) {
            list.add(item.showName)
        }
        mCustomSelectDialog!!.setItemData(list).setSelectIndex(mIsslamicSelectIndex).setTitle(
            DynamicResourceManager.getString(
                mContext, string.isslamic_account
            )
        ).setCallBack { position ->
            list.getOrNull(position)?.also { itemData ->
                mEtIsslamicAccount.text = itemData
                mIsslamicSelectIndex = position
            }
            checkButtonEnable()
        }.show()
    }

    /**
     * 展示性别选择
     */
    private fun showGenderDialog() {
        if (mCustomSelectDialog == null) {
            mCustomSelectDialog = CustomSelectDialog(mContext)
        }
        val list = mutableListOf<String>()
        for (gender in Gender.entries) {
            list.add(gender.showName)
        }
        mCustomSelectDialog!!.setSelectIndex(mGenderSelectIndex).setItemData(list)
            .setTitle(DynamicResourceManager.getString(mContext, string.gender))
            .setCallBack { position ->
                list.getOrNull(position)?.also { itemData ->
                    mEtGender.text = itemData
                    mGenderSelectIndex = position
                }
                checkButtonEnable()
            }.show()
    }

    private fun sendCode() {
        if (!checkInput(mEtEmail)) {
            return
        }
        sendCode(
            SendCodeRequest(
                loginEmail = mEtEmail.text.toString(), businessType = 15
            )
        )
    }

    private fun sendCode(request: SendCodeRequest) {
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mIsShowLoading = true
        mCommonPresenter.execSendCode(request, userToken)
    }

    private fun startCountDown() {
        val resendText = DynamicResourceManager.getString(mContext, string.resend)
        mActivity.countDown(time = 60, start = {
            mCountDown = it
            mTvSendCode.isEnabled = false
        }, end = {
            mTvSendCode.text = resendText
            mTvSendCode.isEnabled = true
        }, next = {
            mTvSendCode.text = "${it}s"
        }, error = {
            mTvSendCode.isEnabled = true
        })
    }


    /**
     * 展示地区选择弹框
     */
    private fun showCountryCodeDialog() {
        if (mCountryCodeDialog == null) {
            mCountryCodeDialog = UFCountryCodeSelectDialogFragment.newInstance(mContext)
            mCountryCodeDialog!!.setCallBack { countryInfo ->
                countryInfo.also {
                    when (mCurrentCountryId) {
                        R.id.rl_country_input_container -> {
                            mEtCountry.text = it.nameEn
                            mCountryInfo = it
                            setShowIsslamicInput(countryInfo)
                            setShowFirstSecondName(countryInfo)
                        }

                        R.id.ll_country_code -> {
                            mPhoneCountryInfo = it
                            mTvCountryCode.text = it.areaCode
                            ExtentUtil.setPhoneDynamicPaddingLeft(mContext, mEtPhone, it.areaCode)
                        }
                    }
                    checkButtonEnable()
                }
            }
        }
        if (mCountryCodeDialog!!.dialog == null || !mCountryCodeDialog!!.dialog!!.isShowing) {
            mCountryCodeDialog!!.show(
                supportFragmentManager, UFCountryCodeSelectDialogFragment::class.java.simpleName
            )
        }
    }

    private fun setShowFirstSecondName(countryInfo: CountryInfo) {
        //中国大陆或香港
        if (SHOW_PINYIN_LIST.contains(countryInfo.code)) {
            val firstInputValue = mEtFirstName.text.toString()
            val secondInputValue = mEtSecondName.text.toString()
            val firstNamePinyin = Utils.convertToPinyin(firstInputValue)
            val secondNamePinyin = Utils.convertToPinyin(secondInputValue)
            mEtFirstName.setText(firstNamePinyin)
            mEtSecondName.setText(secondNamePinyin)
            mEtOtherFirstName.setText("")
            mEtOtherSecondName.setText("")
            mLlOtherFirstNameContainer.visibility = View.VISIBLE
            mLlOtherSecondNameContainer.visibility = View.VISIBLE
            mTvFirstNameTitle.text =
                DynamicResourceManager.getString(mContext, string.first_name_pinyin)
            mTvSecondNameTitle.text =
                DynamicResourceManager.getString(mContext, string.second_name_pinyin)
            mTvOtherFirstNameTitle.text =
                DynamicResourceManager.getString(mContext, string.first_name_chinese)
            mTvOtherSecondNameTitle.text =
                DynamicResourceManager.getString(mContext, string.second_name_chinese)
        } else if (SHOW_KOREAN_LIST.contains(countryInfo.code)) {
            //韩国
            mEtFirstName.setText("")
            mEtSecondName.setText("")
            mEtOtherFirstName.setText("")
            mEtOtherSecondName.setText("")
            mLlOtherFirstNameContainer.visibility = View.VISIBLE
            mLlOtherSecondNameContainer.visibility = View.VISIBLE
            mTvFirstNameTitle.text = DynamicResourceManager.getString(mContext, string.first_name)
            mTvSecondNameTitle.text =
                DynamicResourceManager.getString(mContext, string.second_name)
            mTvOtherFirstNameTitle.text =
                DynamicResourceManager.getString(mContext, string.first_name_korean)
            mTvOtherSecondNameTitle.text =
                DynamicResourceManager.getString(mContext, string.second_name_korean)
        } else {
            mTvFirstNameTitle.text = DynamicResourceManager.getString(mContext, string.first_name)
            mTvSecondNameTitle.text =
                DynamicResourceManager.getString(mContext, string.second_name)
            mLlOtherFirstNameContainer.visibility = View.GONE
            mLlOtherSecondNameContainer.visibility = View.GONE
            mEtFirstName.setText("")
            mEtSecondName.setText("")
            mEtOtherFirstName.setText("")
            mEtOtherSecondName.setText("")
        }
    }

    /**
     * 根据居住地区判断是否显示伊斯兰账户选项
     */
    private fun setShowIsslamicInput(countryInfo: CountryInfo) {
        if (SHOW_ISSLAMIC_ACCOUNT_LIST.contains(countryInfo.code)) {
            mLlIsslamicAccountContainer.visibility = View.VISIBLE
        } else {
            mLlIsslamicAccountContainer.visibility = View.GONE
            mEtIsslamicAccount.text = ""
        }
    }

    /**
     * 选择生日的弹框
     */
    @SuppressLint("SetTextI18n")
    private fun showDatePickDlg() {
        // 设置最大可选日期为18年前
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.YEAR, -18)
        val datePicker = DatePickerDialog(
            mContext,
            { _, year, month, day ->
                val selectedCalendar = Calendar.getInstance().apply {
                    set(year, month, day)
                }
                val currentCalendar = Calendar.getInstance()
                val selectedPlus18 = Calendar.getInstance().apply {
                    timeInMillis = selectedCalendar.timeInMillis
                    add(Calendar.YEAR, 18)
                }
                val isAdult = !currentCalendar.before(selectedPlus18)
                if (isAdult) {
                    // 处理有效的日期选择
                    mEtBirthday.text = selectedCalendar.formatToDateString()
                    checkButtonEnable()
                }
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH) + 1,
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        datePicker.datePicker.maxDate = calendar.timeInMillis
        datePicker.show()
    }

    override fun handleSendCode(response: ResponseResult<Any?>) {
        mIsShowLoading = false
        if (response.code == ResponseResult.SUCCESS_CODE) {
            startCountDown()
            ToastUtils.longToast(
                DynamicResourceManager.getString(
                    mContext, string.send_code_success
                )
            )
        } else {
            LogUtils.e(
                FirstStepOpenAccountActivity::class.java.simpleName,
                "handleSendCode error code: ${response.code} msg: ${response.msg}"
            )
            if (ApiException.isTimeout(response.code)) {
                response.toastTimeout()
            } else {
                response.toast()
            }
        }
    }

    override fun handleFirstStep(response: ResponseResult<Any?>) {
        hideLoading()
        mIsShowLoading = false

        if (response.code == ResponseResult.SUCCESS_CODE) {
            //更新SystemUserInfo
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_USR_INFO)
            GlobalInfoManager.getInstance().addListener(this)
        } else {
            LogUtils.d(
                FirstStepOpenAccountActivity::class.java.simpleName,
                "handleFirstStep error->$response"
            )
            response.toast()
        }
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }
}